package com.ztesoft.sca.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleDetailRequest;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleDetailResponse;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleRequest;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleResponse;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleResponse.Data;
import com.aliyuncs.qualitycheck.model.v20160801.GetRuleResponse.Data.RuleInfo;
import com.ztesoft.sca.common.Constants;
import com.ztesoft.sca.common.SysConstant;
import com.ztesoft.sca.dao.RuleDao;
import com.ztesoft.sca.model.RuleModel;
import com.ztesoft.sca.service.RuleService;
import com.ztesoft.sca.util.exception.ExceptionUtil;
import com.ztesoft.sca.util.message.ResponseUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
 * 质检规则处理 
 * zxz 
 * */

@RestController
public class RuleController {
	private static final Logger logger = Logger.getLogger(AiChatAudioController.class);

    @Autowired
    private RuleService ruleService; 
	
	/*
	 * 获取用户规则
	 * */
	@RequestMapping(value = "/aichat/SCAGetUserRules",method = {RequestMethod.POST})
	public String scaUserRules(@RequestBody String requestBody,HttpServletRequest request) throws Exception {
		List<String> ruleIdList=new ArrayList<>();
        JSONObject jsonList = JSONObject.fromObject(requestBody);
		if(jsonList == null){
			return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR,Constants.INF_DESC_NULL_REQUESTBODY);
		}
        
        JSONArray ruleIdListData = jsonList.getJSONArray("ruleIds");
        for (int i = 0; i < ruleIdListData.size(); i++) {  
        	ruleIdList.add(ruleIdListData.getString(i)); 
        }
        
        Data jsonData =null;
        List<RuleInfo> resultGet=null;
		
		IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
		try {
			DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		IAcsClient client = new DefaultAcsClient(profile);
		
        GetRuleRequest getRuleRequest = new GetRuleRequest();
        getRuleRequest.setAcceptFormat(FormatType.JSON);
        Map<String, Object> callMap =  new HashMap<String, Object>();
        callMap.put("appKey", SysConstant.APP_KEY);
        callMap.put("ruleIds", ruleIdList);
       // callMap.put("businessCategoryName", Arrays.asList("业务A"));
        callMap.put("isDelete", 0);
        callMap.put("status", 1);
        getRuleRequest.setJsonStr(JSON.toJSONString(callMap));
        GetRuleResponse response = client.getAcsResponse(getRuleRequest);
        resultGet=response.getData().getRules();
        
        jsonData = response.getData();
       
       //查询用户规则ID
       List<RuleModel> dataIdStr=this.ruleService.selectDataRuleList();
       String dataStr="";
       for(RuleModel  stu :  dataIdStr ){
       		dataStr=dataStr+","+stu.getRid();
   		}
       
       JSONObject json = JSONObject.fromObject(jsonData);
       JSONArray  jsonDataSet = json.getJSONArray("rules");

       //获取阿里云的规则批量入库
   	   SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   	   SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); 
   	   
       List<RuleModel> listUpdate = new ArrayList<RuleModel>();
       List<RuleModel> list = new ArrayList<RuleModel>();
       for (int i = 0; i < resultGet.size(); i++) {  
	       	String ridStr=resultGet.get(i).getRid();
	       	Long rid= Long.parseLong(resultGet.get(i).getRid());
	       	Long bid=0l;
	       	String ruleName=resultGet.get(i).getName();
	       	int status=resultGet.get(i).getStatus();
	       	int autoReview=resultGet.get(i).getAutoReview();
	       	int ruleScoreType=resultGet.get(i).getRuleScoreType();
	       	String scoreName=resultGet.get(i).getScoreName();
	       	String scoreSubname=resultGet.get(i).getScoreSubName();
	       	String comments=resultGet.get(i).getComments();
	       
	       	String dstr=resultGet.get(i).getCreateTime();
	        
	        java.util.Date date= sd.parse(dstr);  
	        String str=sdf.format(date); 
	        java.util.Date createTime=sdf.parse(str);
	       	int isDelete=resultGet.get(i).getIsDelete();
	       	//更新
	       	if(dataStr.indexOf(ridStr)>-1){
		        listUpdate.add(new RuleModel(rid,bid,ruleName,status,autoReview,ruleScoreType,scoreName,scoreSubname,comments,createTime,isDelete));
	       	}else{
	       	//首次入库
	       		list.add(new RuleModel(rid,bid,ruleName,status,autoReview,ruleScoreType,scoreName,scoreSubname,comments,createTime,isDelete));
	       	} 
       } 
       
     //新增数据到本地库
       try {
			this.ruleService.updateRuleData(listUpdate);
			this.ruleService.addRuleData(list);
		} catch (Exception e) {
			 logger.error(" jsonData occur an error!",e);
			 return ResponseUtils.feedback(Constants.INF_CODE_ERROR,Constants.INF_DESC_ERROR, ExceptionUtil.getMessage(e));
		}
       //返回所有数据到前台
        
        logger.info("----获取用户----"+resultGet); 
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,jsonData);
	}
	
	/*
	 * 获取规则明细
	 * */
	@RequestMapping(value = "/aichat/SCAGetDetailRules")
	public String scaDetailRules() throws ServerException, ClientException {
		List<String> ruleIdList=new ArrayList<>();
		ruleIdList.add("130");
		
		IClientProfile profile = DefaultProfile.getProfile(SysConstant.REGION_ID, SysConstant.ACCESS_KEY_ID, SysConstant.ACCESS_KEY_SECRET);
		try {
			DefaultProfile.addEndpoint(SysConstant.ENDPOINT_NAME, SysConstant.REGION_ID, SysConstant.PRODUCT, SysConstant.DOMAIN);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		IAcsClient client = new DefaultAcsClient(profile);
        GetRuleDetailRequest getRuleDetailRequest = new GetRuleDetailRequest();
        getRuleDetailRequest.setAcceptFormat(FormatType.JSON);
        
        Map<String, Object> callMap =  new HashMap<String, Object>();
        callMap.put("appKey", SysConstant.APP_KEY);
        //callMap.put("ruleIds", ruleIdList);
        callMap.put("isDelete", 0);
        callMap.put("status", 1);
        getRuleDetailRequest.setJsonStr(JSON.toJSONString(callMap));
        GetRuleDetailResponse response = client.getAcsResponse(getRuleDetailRequest);
        String resultGet = JSON.toJSONString(response);
        
        logger.info("----获取规则明细----"+resultGet); 
        return ResponseUtils.feedback(Constants.INF_CODE_SUCC,Constants.INF_DESC_SUCC,resultGet);
	}
}
